﻿namespace _3_NovaAdmin.Domain.ToolKits.Extensions;

/// <summary>
/// 判断类型是否继承自某个泛型定义
/// </summary>
public static class TypeExtensions
{
    public static bool IsAssignableToGenericType(this Type type, Type genericTypeDefinition)
    {
        if (type == null) throw new ArgumentNullException(nameof(type));
        if (!genericTypeDefinition.IsGenericTypeDefinition)
            throw new ArgumentException("必须提供泛型类型定义", nameof(genericTypeDefinition));

        // 遍历类型及其所有基类
        var currentType = type;
        while (currentType != null && currentType != typeof(object))
        {
            if (currentType.IsGenericType &&
                currentType.GetGenericTypeDefinition() == genericTypeDefinition)
            {
                return true;
            }

            // 检查实现的接口
            if (currentType.GetInterfaces().Any(it =>
                it.IsGenericType &&
                it.GetGenericTypeDefinition() == genericTypeDefinition))
            {
                return true;
            }

            currentType = currentType.BaseType;
        }
        return false;
    }
}
